/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import DAO.Util.CauHoiDAO;
import Pojo.CauHoi;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.w3c.dom.*;
import org.xml.sax.SAXException;

/**
 *
 * @author ducquyen
 */
@WebServlet(name = "UploadCauHoicontroller", urlPatterns = {"/UploadCauHoicontroller"})
public class UploadCauHoicontroller extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        //PrintWriter out = response.getWriter();
        try {

            String action = request.getParameter("Action");
            if (action != null) {
                if (action.equals("View")) {
                    request.getRequestDispatcher("/UploadCauHoi.jsp").forward(request, response);
                }
                if (action.equals("Upload")) {
                    int soLuongCauHoi = 0;
                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                    if (!isMultipart) {
                        throw new ServletException("Dung sai dang form");
                    }
                    // Create a factory for disk-based file items

                    //Dung tham so mac dinh
                    FileItemFactory factory = new DiskFileItemFactory();
                    //Tinh chinh tham so, xem them tai lieu
                    //FileItemFactory factory = new DiskFileItemFactory(1024,new java.io.File("C:/upload"));
                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(factory);

                    // Parse the request
                    List items = upload.parseRequest(request);
                    ListIterator iterator = items.listIterator();
                    while (iterator.hasNext()) {
                        FileItem item = (FileItem) iterator.next();
                        if (item.isFormField()) {
                            String name = item.getFieldName();
                            String value = item.getString("utf-8");
                            //out.println("name=" + name + ",value=" + value + "<br/>");
                        } else {//Ten file, doc XML
                            try {
                                //item.getInputStream();

                                //InputStreamReader reader = new InputStreamReader(item.getInputStream(), "utf-8");
                                //InputSource source = new InputSource(reader);

                                DocumentBuilderFactory factorylocal = DocumentBuilderFactory.newInstance();
                                DocumentBuilder builderlocal = factorylocal.newDocumentBuilder();
                                Document doclocal = builderlocal.parse(CauHoiDAO.layDuongDanTapTinCauHoi());


                                DocumentBuilderFactory factoryxml = DocumentBuilderFactory.newInstance();
                                DocumentBuilder builder = factoryxml.newDocumentBuilder();
                                Document doc = builder.parse(item.getInputStream());

                                Element root = doc.getDocumentElement();
                                NodeList list = root.getChildNodes();
                                soLuongCauHoi = list.getLength();
                                for (int i = 0; i < list.getLength(); i++) {
                                    Node node = list.item(i);
                                    if (node instanceof Element) {
                                        Element element = (Element) node;
                                        CauHoi ch = new CauHoi();
                                        ch.setMaCauHoi(CauHoiDAO.layMaCauHoiTuFile(doclocal));
                                        //ch.setMaCauHoi(Integer.parseInt(element.getAttribute("MaCauHoi")));
                                        NodeList elist = element.getChildNodes();
                                        for (int j = 0; j < elist.getLength(); j++) {
                                            Node enode = elist.item(j);
                                            if (enode instanceof Element) {
                                                Element ele = (Element) enode;
                                                Text textNode = (Text) ele.getFirstChild();
                                                String content = textNode.getData();
                                                switch (ele.getTagName()) {
                                                    case "NoiDung":
                                                        ch.setNoiDungCauHoi(content);
                                                        break;
                                                    case "LuaChon1":
                                                        ch.setLuaChon1(content);
                                                        break;
                                                    case "LuaChon2":
                                                        ch.setLuaChon2(content);
                                                        break;
                                                    case "LuaChon3":
                                                        ch.setLuaChon3(content);
                                                        break;
                                                    case "LuaChon4":
                                                        ch.setLuaChon4(content);
                                                        break;
                                                    case "DapAn":
                                                        ch.setCauDung(Integer.parseInt(content));
                                                        break;
                                                    case "DoKho":
                                                        ch.setDoKho(Integer.parseInt(content));
                                                        break;
                                                }

                                            }

                                        }
                                        //Add cau hoi vao list 
                                        //arrCauHoi.add(ch);
                                        CauHoiDAO.themCauHoi(doclocal, ch);
                                    }

                                }

                            } catch (ParserConfigurationException | SAXException | IOException | NumberFormatException | DOMException | TransformerException e) {
                                request.getRequestDispatcher("/UploadCauHoi.jsp?UploadThanhCong=0").forward(request, response);
                            }
                        }
                    }


                    request.getRequestDispatcher("/UploadCauHoi.jsp?UploadThanhCong=1&SoLuongCauHoi=" + soLuongCauHoi).forward(request, response);
                }

                if (action.equals("Download")) {

                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment;filename=CauHoi.xml");
                    File file = new File(CauHoiDAO.layDuongDanTapTinCauHoi());
                    FileInputStream fileIn = new FileInputStream(file);
                    ServletOutputStream out = response.getOutputStream();

                    byte[] outputByte = new byte[4*1024];
                    int byteRead = 0;

                    while ((byteRead=fileIn.read(outputByte, 0, 1024)) != -1) {
                        out.write(outputByte, 0, byteRead);
                    }
                    fileIn.close();
                    //out.flush();
                    //out.close();
                    request.getRequestDispatcher("/UploadCauHoi.jsp").forward(request, response);
                }

            }




        } finally {
            //out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadCauHoicontroller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(UploadCauHoicontroller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
